#!/usr/bin/env python

# Copyright (c) 2023 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.  messages=[{
#             'role': 'user',
#             'content': "请问你是谁？"
#         }, {
#             'role': 'assistant',
#             'content':
#                 "我是百度公司开发的人工智能语言模型，我的中文名是文心一言，英文名是ERNIE-Bot，可以协助您完成范围广泛的任务并提供有关各种主题的信息，比如回答问题，提供定义和解释及建议。如果您有任何问题，请随时向我提问。"
#         }, {
#             'role': 'user',
#             'content': "我在深圳，周末可以去哪里玩？"
#         }],
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


import erniebot
from erniebot.utils.logging import logger
from flask_cors import CORS
from flask import Flask,request
app=Flask(__name__)
CORS(app,resources={r"/*":{"origins":"*"}})



API_KEY = "90mGcXXXnmGgnRbleg5GXxK2"
SECRET_KEY = "8WNvBUU43eXiiA2O2RRvVBFmW1z5HgZv"
import requests
import json
import re



def create_chat_completion(model,content,expression):
    expressionContent="开心的"
    if(expression==0):
        expressionContent="愤怒的"
    if(expression==1):
        expressionContent="反感的"
    if(expression==2):
        expressionContent="害怕的"
    if(expression==3):
        expressionContent="开心的"
    if(expression==4):
        expressionContent="自然的"
    if(expression==5):
        expressionContent="伤心的"
    if(expression==6):
        expressionContent="惊讶的"
    tpMessage=content[2].get("content")
    content[2]["content"]="现在我的心情是{}，{}".format(expressionContent,tpMessage)
    print(content)

    response = erniebot.ChatCompletion.create(
        model=model,
        messages=content,
        stream=False)
    print(response.get_result())
    return response.get_result()


# def create_chat_completion_stream(model):
#     response = erniebot.ChatCompletion.create(
#         model=model,
#         messages=[{
#         #     'role': 'user',
#         #     'content': "请问你是谁？"
#         # }, {
#         #     'role': 'assistant',
#         #     'content':
#         #         "我是百度公司开发的人工智能语言模型，我的中文名是文心一言，英文名是ERNIE-Bot，可以协助您完成范围广泛的任务并提供有关各种主题的信息，比如回答问题，提供定义和解释及建议。如果您有任何问题，请随时向我提问。"
#         # }, {
#             'role': 'user',
#             'content': "我在深圳，周末可以去哪里玩？"
#         }],
#         stream=True)
#
#     for item in response:
#         sys.stdout.write(item.get_result())
#         sys.stdout.flush()
#     sys.stdout.write('\n')

@app.route("/getResponse",methods=['POST'])
def getResponse():
    logger.set_level('WARNING')
    erniebot.api_type = 'aistudio'
    erniebot.access_token = '6a4f918251cd45d4c2ae0a7f7dac65110311358c'
    str=''
    tpContent=request.json
    expression=request.headers.get("index")
    str+=create_chat_completion(model='ernie-bot-turbo',content=tpContent,expression=5)
    arr=[]
    arr.append(str)
    print(arr)
 # create_chat_completion_stream(model='ernie-bot-turbo')



#生成图片
#生成图片
#生成图片
#生成图片
#生成图片
#生成图片
#
#
# def image_generate(val,type):
#     url = "https://aip.baidubce.com/rpc/2.0/ernievilg/v1/txt2img?access_token=" + get_access_token()
#
#     payload = json.dumps({
#         "text": val,
#         "resolution": "1024*1024",
#         "style": "{}".format(type)
#     })
#     headers = {
#         'Content-Type': 'application/json',
#         'Accept': 'application/json'
#     }
#     response = requests.request("POST", url, headers=headers, data=payload)
#     print(response.text)
#     task_id = ''
#     data = response.text
#     pattern = r'"taskId":(\d+)'
#     match = re.search(pattern, data)
#
#     if match:
#         task_id = match.group(1)
#         print(task_id)
#     else:
#         print("未找到taskId")
#     return task_id
#
# def get_access_token():
#     """
#     使用 AK，SK 生成鉴权签名（Access Token）
#     :return: access_token，或是None(如果错误)
#     """
#     url = "https://aip.baidubce.com/oauth/2.0/token"
#     params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}
#     return str(requests.post(url, params=params).json().get("access_token"))
#
# @app.route("/getImg",methods=['POST'])
# def main():
#     value=request.json
#     print(value.get("value"))
#     print(value.get("type"))
#     text=value.get("value")
#     type=value.get("type")
#     task_id = image_generate(text,type)
#     print(task_id)
#     url = "https://aip.baidubce.com/rpc/2.0/ernievilg/v1/getImg?access_token=" + get_access_token()
#     payload = json.dumps({
#         "taskId": task_id
#     })
#     headers = {
#         'Content-Type': 'application/json',
#         'Accept': 'application/json'
#     }
#
#     response = requests.request("POST", url, headers=headers, data=payload)
#     print(response.text)
#     # 解析JSON数据
#     parsed_data = json.loads(response.text)
#
#     # 提取 "img" 和 "imgUrls" 字段的值
#     img_url = parsed_data["data"]["img"]
#     img_urls = [item["image"] for item in parsed_data["data"]["imgUrls"]]
#
#     print("img:", img_url)
#     print("imgUrls:", img_urls)
#     return img_urls
